import json
import csv

json_file = 'db_info.json'
csv_file = 'db_info.csv'


def txt_json():
    # 平面文件
    data = {}
    lines = []
    # 获取键
    with open(csv_file, 'r') as f:
        lines = f.readlines()
    keys = lines[0].rstrip('\n').split(':')

    # 遍历剩余的行并转换为字典
    for line in lines[1:]:
        values = line.rstrip('\n').split(':')
        entry = {key: value for key, value in zip(keys, values)}
        db_key = entry["dbname"][3:6].upper()
        user_kye = entry["username"].upper()
        if not data.get(db_key):
            data[db_key] = {}
        # 将用户信息添加到对应的 DB 下
        data[db_key][user_kye] = entry

    # 转换为 JSON 格式
    json_output = json.dumps(data, indent=4)

    # 将 JSON 输出写入到文件中
    with open(json_file, 'w') as f:
        f.write(json_output)

    print(f"JSON 数据已写入 {json_file}")


def csv_json():
    data = {}
    with open(csv_file, mode='r', newline='', encoding='utf-8') as f:
        # 创建一个CSV reader对象，并跳过标题行（可选，但在这个例子中我们不需要显式跳过，因为我们会从第一行开始构建字典）
        csv_reader = csv.DictReader(f)

        # 遍历CSV文件的每一行
        for row in csv_reader:
            # 提取数据库名、用户名和其他信息
            db = row['dbname'][3:6].upper()
            user = row['username'].upper()

            # 如果数据库名不在字典中，则添加一个新的空字典
            if db not in data:
                data[db] = {}

            data[db][user] = row

    # 转换为 JSON 格式
    json_output = json.dumps(data, indent=4)

    # 将 JSON 输出写入到文件中
    with open(json_file, 'w') as f:
        f.write(json_output)

    print(f"JSON 数据已写入 {json_file}")


def json_csv():
    data = {}
    with open(json_file, 'r') as js:
        data = json.load(js)

    # 创建一个 CSV 文件并写入数据
    with open(csv_file, 'w', newline='') as f:
        # 定义 CSV 文件的字段名 "ip:port:dbname:username:pwd:new_pwd"
        fieldnames = ["ip", "port", "dbname", "username", "pwd", "sid", "url", "db_type", "driver"]
        writer = csv.DictWriter(f, fieldnames=fieldnames)

        # 写入表头
        writer.writeheader()

        # 遍历 JSON 数据并写入 CSV
        for db_name, users in data.items():
            for user_name, user_info in users.items():
                writer.writerow(user_info)

    print(f"JSON 数据已成功转换并写入 {csv_file}")


csv_json()
